package com.gitee.neuray.security.mail.biz;

import cn.hutool.extra.mail.MailUtil;
import com.gitee.neuray.security.common.biz.BaseBiz;
import com.gitee.neuray.security.common.util.CommonUtil;
import com.gitee.neuray.security.common.util.EntityUtils;
import com.gitee.neuray.security.mail.entity.SysMailSource;
import com.gitee.neuray.security.mail.mapper.MailMapper;
import com.gitee.neuray.security.mail.util.BirthDayUtil;
import com.gitee.neuray.security.mail.util.EmailCommon;
import com.gitee.neuray.security.mail.util.EmailUtil;
import com.gitee.neuray.security.mail.vo.BirthDayVo;
import com.gitee.neuray.security.mail.vo.SendStausVo;
import com.gitee.neuray.security.mail.vo.SysMailSourceVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.*;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @auther: zhuqz
 * @date: 2020/2/26 09:52
 * @description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MailBiz extends BaseBiz<MailMapper, SysMailSource> {
    Logger logger = LoggerFactory.getLogger(MailBiz.class);
    @Autowired
    MailMapper mailMapper;
    @Value("${ehrMail}")
    private String ehrMail;
    @Value("${ehrPwd}")
    private String ehrPwd;
    @Value("${mailServer}")
    private String mailServer;
    @Value("${defaultMailSuffix}")
    private String defaultMailSuffix;
    @Override
    protected String getPageName() {
        return null;
    }

    public int add(SysMailSourceVo vo) throws  Exception{
        EntityUtils.setCreatAndUpdatInfo(vo);
        //模板
        if(vo.getYjnrType()==null || "".equals(vo.getYjnrType())){
            vo.setYjnrType("0");//默认是文本类型模板
        }
        if(vo.getYjnrType().equals("1")){//如果是blob模板
            //object->byte[]
            byte[] bytes = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(vo.getYjnrBl());
                oos.flush();
                bytes = bos.toByteArray ();
                oos.close();
                bos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            vo.setYjnrBl(bytes);
        }
        int i = this.mailMapper.add(vo);

        return 1;
    }
    public SysMailSourceVo queryById(String id) throws Exception{
        SysMailSourceVo vo = this.mailMapper.queryById(id);
        if("1".equals(vo.getYjnrType())){//如果是blob类型模板
            Blob blob = (Blob) vo.getYjnrBl();//读取blob字段
            //BLob->byte[]
            BufferedInputStream is = null;
            is = new BufferedInputStream(blob.getBinaryStream());
            byte[] bytes = new byte[(int) blob.length()];
            int len = bytes.length;
            int offset = 0;
            int read = 0;
            while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
                offset += read;
            }
            //byte->object
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            Object obj = ois.readObject();
            ois.close();
            bis.close();
            System.out.println(obj.toString());
            vo.setYjnrBl(obj);
        }
        return vo;
    }

    /**
     * 定时发送邮件
     * @return
     * @throws Exception
     */
    public SendStausVo sendTimerMail() throws Exception{
        logger.info("==============================================================邮件定时任务！");
        SendStausVo sendStausVo = new SendStausVo();
        List<SysMailSourceVo> mailList = this.mailMapper.getMailListToSend();
        sendStausVo.setTotalCount(mailList.size());//一共多少邮件
        int count = 0;//发送成功多少
        for(int i=0;i<mailList.size();i++){
            SysMailSourceVo vo = mailList.get(i);
            String id = vo.getId();
            String content = vo.getYjnrTe();
            String sjr = vo.getSjr();// 收件人，多个收件人以半角逗号分隔
            String csr = vo.getCsr();// 抄送，多个抄送以半角逗号分隔
            String asr = vo.getAsr();// 暗送，多个抄送以半角逗号分隔
            String title = vo.getTitle();
            String fileid = vo.getFjid();
            //todo blob模板待处理
            if("1".equals(vo.getYjnrType())){//如果是blob类型模板
                Blob blob = (Blob) vo.getYjnrBl();//读取blob字段
                //BLob->byte[]
                BufferedInputStream is = null;
                is = new BufferedInputStream(blob.getBinaryStream());
                byte[] bytes = new byte[(int) blob.length()];
                int len = bytes.length;
                int offset = 0;
                int read = 0;
                while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
                    offset += read;
                }
                //byte->object
                ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
                ObjectInputStream ois = new ObjectInputStream (bis);
                Object obj = ois.readObject();
                ois.close();
                bis.close();
                content = obj.toString();
            }
            //去重复
            sjr = dealMailDuplicate(sjr);
            csr = dealMailDuplicate(csr);
            asr = dealMailDuplicate(asr);
            //todo 附件处理
            //发送邮件
            try {
                //List<String> attachments = Arrays.asList("D:\\tmp\\1.png", "D:\\tmp\\2.png"); // 附件的路径，多个附件也不怕
                EmailUtil email = EmailUtil.entity(mailServer, ehrMail+"@"+defaultMailSuffix, ehrPwd, sjr, csr, asr, title, content, null);
                email.send(); // 发送
                this.mailMapper.setMailStatus(id,"1","");//发送成功
                count++;
            }catch (Exception e){
                e.printStackTrace();;
                logger.error("==============================================================邮件发送错误！");
                logger.error(CommonUtil.getExceptionDtail(e));
                sendStausVo.setStatus(false);//有失败邮件
                sendStausVo.setMsg(sendStausVo.getMsg()+"服务器错误 ");//失败原因
                this.mailMapper.setMailStatus(id,"0","服务器出错！");//发送成功
            }
        }
        sendStausVo.setSendCount(count);
        return sendStausVo;
    }

    /**
     * 邮件去重复
     * @param mails
     * @return
     */
    private String dealMailDuplicate(String mails){
        if(mails==null || "".equals(mails) || ",".equals(mails)){
            return "";
        }
        String newMail = "";
        List<String> mailList = Arrays.asList(mails.split(","));
        for(String mail:mailList){
            if(mail==null || "".equals(mail)){
                continue;
            }
            String[] mailParts = mail.split("@");
            String suffix = "@"+defaultMailSuffix;
            if(mailParts.length==2){
                suffix = "@"+mailParts[1].toLowerCase();
            }
            mail = mailParts[0]+suffix;
            if(newMail.indexOf(mail)==-1){
                newMail+=","+mail;
            }
        }
        if("".equals(newMail)){
            return newMail;
        }
        return newMail.substring(1);
    }

    /**
     * 定时发送生日邮件
     * @return
     * @throws Exception
     */
    public SendStausVo sendBirthdayTimerMail() throws Exception{
        logger.info("==============================================================生日邮件定时任务！");
        SendStausVo sendStausVo = new SendStausVo();
        List<BirthDayVo> mailList = this.mailMapper.getBirthDayMailListToSend();
        sendStausVo.setTotalCount(mailList.size());//一共多少邮件
        logger.info("==============================================================生日邮件多少封："+mailList.size());
        if(mailList.size()==0){
            sendStausVo.setSendCount(0);
            logger.info("==============================================================生日邮件发送结束！");
            return sendStausVo;
        }
        String season1 = "";//图片1
        String season2 = "";//图片2
        String season3 = "";//图片3
        Random rand = new Random();
        int ri = rand.nextInt(10)+1;//1-10
        season1 = "birthday"+ri+".jpg";
        while (season2.equals("") || season2.equals(season1)){
             rand = new Random();
             ri = rand.nextInt(10)+1;//1-10
            season2 = "birthday"+ri+".jpg";
        }
        while (season3.equals("") || season3.equals(season1) || season3.equals(season2)){
            rand = new Random();
            ri = rand.nextInt(10)+1;//1-10
            season3 = "birthday"+ri+".jpg";
        }


        ClassPathResource resource1 = null;
        try {
            resource1 = new ClassPathResource("birthpic/"+season1);
        } catch (Exception e) {
            logger.error("读取文件错误");
            resource1 = new ClassPathResource("birthpic/birthday1.jpg");
        }
        ClassPathResource resource2 = null;
        try {
            resource2 = new ClassPathResource("birthpic/"+season2);
        } catch (Exception e) {
            logger.error("读取文件错误");
            resource2 = new ClassPathResource("birthpic/birthday1.jpg");
        }
        ClassPathResource resource3 = null;
        try {
            resource3 = new ClassPathResource("birthpic/"+season3);
        } catch (Exception e) {
            logger.error("读取文件错误");
            resource3 = new ClassPathResource("birthpic/birthday1.jpg");
        }
        season1 = EmailCommon.fileToBytesToBase64(resource1.getInputStream());
        season2 = EmailCommon.fileToBytesToBase64(resource2.getInputStream());
        season3 = EmailCommon.fileToBytesToBase64(resource3.getInputStream());

        int count = 0;//发送成功多少
        for(int i=0;i<mailList.size();i++){
            BirthDayVo vo = mailList.get(i);
            String sjr  = vo.getEmail();
            String name = vo.getName();
            //String content = BirthDayUtil.getTemplate(name,season1,season2,season3);
            String content = "";
            String asr = BirthDayUtil.asr;

            //发送邮件
            try {
                //List<String> attachments = Arrays.asList("D:\\tmp\\1.png", "D:\\tmp\\2.png"); // 附件的路径，多个附件也不怕
                EmailUtil email = EmailUtil.entity(mailServer, ehrMail+"@"+defaultMailSuffix, ehrPwd, sjr, null, asr, "生日祝福", content, null);
                email.send(); // 发送
                count++;
            }catch (Exception e){
                e.printStackTrace();;
                logger.error("==============================================================生日邮件发送错误！");
                logger.error(CommonUtil.getExceptionDtail(e));
                sendStausVo.setStatus(false);//有失败邮件
                sendStausVo.setMsg(sendStausVo.getMsg()+"服务器错误 ");//失败原因
            }
        }
        sendStausVo.setSendCount(count);
        logger.info("==============================================================生日邮件发送结束！");
        return sendStausVo;
    }
    /**生日邮件1成功0失败*/
    public int addBirthdayTimerMail() throws Exception{
        logger.info("==============================================================生日邮件定时任务！");
        List<BirthDayVo> mailList = this.mailMapper.getBirthDayMailListToSend();
        logger.info("==============================================================生日邮件多少封："+mailList.size());
        if(mailList.size()==0){
            logger.info("==============================================================生日邮件定时任务结束！");
            return 1;
        }
        String season1 = "birthday8.jpg";
        String season2 = "cartoon.gif";
        ClassPathResource resource1 = null;
        ClassPathResource resource2 = null;
        try {
            resource1 = new ClassPathResource("birthpic/"+season1);
            resource2 = new ClassPathResource("birthpic/"+season2);
        } catch (Exception e) {
            logger.error("读取文件错误");
            resource1 = new ClassPathResource("birthpic/birthday1.jpg");
        }

        season1 = EmailCommon.fileToBytesToBase64(resource1.getInputStream());
        season2 = EmailCommon.fileToBytesToBase64(resource2.getInputStream());

        for(int i=0;i<mailList.size();i++){
            BirthDayVo bvo = mailList.get(i);
            String sjr  = bvo.getEmail();
            String name = bvo.getName();
            String content = BirthDayUtil.getTemplate(name,season1,season2);
            //添加邮件
            try {
                SysMailSourceVo vo = new SysMailSourceVo();
                vo.setTitle("生日祝福");
                vo.setSjr(sjr);
                vo.setAsr(BirthDayUtil.asr);
                vo.setYjnrType("1");
                vo.setYjnrBl(content);
                vo.setCrtUser("system");
                vo.setCrtName("系统");
                vo.setYjsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                this.add(vo);
            }catch (Exception e){
                e.printStackTrace();;
                logger.error("==============================================================生日邮件定时日任务错误！");
                logger.error(CommonUtil.getExceptionDtail(e));
                return  0;
            }
        }
        logger.info("==============================================================生日邮件定时任务结束！");
        return 1;
    }
    /**
     * 水印
     * @return
     * @throws Exception
     */
    /*public static void test() {
        String season1 = "";//图片1
        Random rand = new Random();
        int ri = rand.nextInt(10)+1;//1-10
        season1 = "birthday8.jpg";

        ClassPathResource resource1 = null;
        try {
            resource1 = new ClassPathResource("birthpic/"+season1);
        } catch (Exception e) {
            resource1 = new ClassPathResource("birthpic/birthday1.jpg");
        }
        try {
            List<String[]> content = new ArrayList<>(16);
            content.add(new String[] {"10","30","朱清昃："});
            content.add(new String[] {"10","50","今天是你的生日，祝你生日快乐，我们一起给你大大的拥抱，送上最温暖的心意。"});
            content.add(new String[] {"10","70","愿过去一年里你所有的努力与付出，都能在今天化作成长的幸福。"});
            content.add(new String[] {"10","90","崭新的下一年，期待我们继续一路同行，分享这段旅途所有的风景和心情！"});
            BirthDayUtil.createMark(EmailCommon.fileToBytes(resource1.getInputStream()),content,new Color(255,66,0),1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    public static void test() {
        String season1 = "";//图片1
        Random rand = new Random();
        int ri = rand.nextInt(10)+1;//1-10
        season1 = "birthday8.jpg";

        ClassPathResource resource1 = null;
        try {
            resource1 = new ClassPathResource("birthpic/"+season1);
        } catch (Exception e) {
            resource1 = new ClassPathResource("birthpic/birthday1.jpg");
        }
        try {
            season1 = EmailCommon.fileToBytesToBase64(resource1.getInputStream());
            String content = BirthDayUtil.getTemplate("朱清昃",season1,"");

            SysMailSourceVo vo = new SysMailSourceVo();
            vo.setTitle("生日祝福");
            vo.setSjr("zhuqz@neuray.com");
            vo.setCsr("");
            vo.setAsr("zhuqz@neuray.com");
            vo.setYjnrType("1");
            vo.setYjnrBl(content);
            vo.setCrtUser("system");
            vo.setCrtName("系统管理员");
            vo.setYjsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //mailMapper.add(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        test();
    }

}